from operator import itemgetter, attrgetter
import pickle
from classCluster import Cluster
from classEdge import Edge
from storeTitles import storeTitles
from storeNodes import storeNodes
import json

def mergeJson(id):
    meta = 'data/result/' + id + '.json'
    svg = 'svgdata/result/' + id + '_svg.json'
    f1 = open(meta, 'r')
    metaData = pickle.load(f1)
    f1.close()
    f2 = open(svg, 'r')
    svgData = pickle.load(f2)
    f2.close()
    dic = {'cluster':{}, 'edge':[]}
    metaData['edge'] = sorted(metaData['edge'], key=attrgetter('target'))
    metaData['edge'] = sorted(metaData['edge'], key=attrgetter('source'))
    svgData['edge'] = sorted(svgData['edge'], key=attrgetter('target'))
    svgData['edge'] = sorted(svgData['edge'], key=attrgetter('source'))
    for key in svgData['cluster'].keys():
        cluster = Cluster()
        cluster.x = svgData['cluster'][key].x
        cluster.y = svgData['cluster'][key].y
        if key != '300':
            cluster.keywords = metaData['cluster'][key].keywords
        cluster.nodes = metaData['cluster'][key].nodes
        tmp_nodeidlist = [(one_node['id'], one_node['year']) for one_node in cluster.nodes]
        #cluster.nodeidlist = metaData['cluster'][key].nodeidlist
        cluster.nodeidlist = tmp_nodeidlist
        dic['cluster'][key] = {
            'keywords': cluster.keywords,
            'nodeidlist': cluster.nodeidlist,
            'nodes': cluster.nodes,
            'x': cluster.x,
            'y': cluster.y
        }
    for i in range(len(svgData['edge'])):
        edge = metaData['edge'][i]
        edge.assists = svgData['edge'][i].assists
        tmp = {
            'PROP_WEIGHT': edge.PROP_WEIGHT,
            'agg_count': edge.agg_count,
            'assists': edge.assists,
            'flow': edge.flow,
            'source': edge.source,
            'target': edge.target,
            'weight': edge.weight
        }
        #print edge.source,edge.target,edge.assists
        dic['edge'].append(tmp)
    dic['cluster']['300']['focused'] = 'true'
    storeTitles(dic, id)
    storeNodes(dic, id)
    #
    dic['cluster']['300']['title'] = dic['cluster']['300']['nodes'][0]['title']
    dic['cluster']['300']['summary'] = dic['cluster']['300']['nodes'][0]['summary']
    #add author+venue information
    for key in list(dic['cluster']):
        dic['cluster'][key]['author_venue'] = dict()
        dic['cluster'][key]['author_venue']['author'] = dic['cluster'][key]['nodes'][0]['firstauthor']
        dic['cluster'][key]['author_venue']['venue'] = dic['cluster'][key]['nodes'][0]['venue']
    #add author information
    for key in list(dic['cluster']):
        tmp_authors = dict()
        for node in dic['cluster'][key]['nodes']:
            if node['firstauthor'] == '' or node['firstauthor'] == ' ' or node['firstauthor'] == 'None':
                continue
            if tmp_authors.get(node['firstauthor']) == None:
                tmp_authors[node['firstauthor']] = 0
            tmp_authors[node['firstauthor']] += 1
        list_tmp_authors = list(tmp_authors)
        list_tmp_authors = sorted(list_tmp_authors, key = tmp_authors.get)
        if len(list_tmp_authors) > 0:
            dic['cluster'][key]['author'] = list_tmp_authors[-1]
        else:
            dic['cluster'][key]['author'] = ''
        print "Author: ", dic['cluster'][key]['author']
    #add venue information
    for key in list(dic['cluster']):
        tmp_venues = dict()
        for node in dic['cluster'][key]['nodes']:
            if node['venue'] == '' or node['venue'] == ' ' or node['venue'] == 'None':
                continue
            if tmp_venues.get(node['venue']) == None:
                tmp_venues[node['venue']] = 0
            tmp_venues[node['venue']] += 1
        list_tmp_venues = list(tmp_venues)
        list_tmp_venues = sorted(list_tmp_venues, key = tmp_venues.get)
        if len(list_tmp_venues) > 0:
            dic['cluster'][key]['venue'] = list_tmp_venues[-1]
        else:
            dic['cluster'][key]['venue'] = ''
        print "Venue: ", dic['cluster'][key]['venue']
    #
    for key in dic['cluster']:
        del dic['cluster'][key]['nodes']
    path = 'json/' + id + '.json'
    f = open(path,'w')
    pickle.dump(dic,f)
    f.close()
    print("all done")
